package com.example.demo.ldap.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.example.demo.constant.HttpStatusCode;
import com.example.demo.exception.BaseServiceException;
import com.example.demo.ldap.entity.Organization;
import com.example.demo.ldap.entity.User;
import com.example.demo.ldap.service.ILdapService;
import com.example.demo.ldap.support.OraganizationMapper;
import com.example.demo.ldap.support.UserAttributesMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.springframework.ldap.query.LdapQueryBuilder.query;

/**
 * @ClassName LadpService
 * @Author b21399
 * @Date 2020/11/19 10:46
 * @Description TODO
 * @Version 1.0
 **/
@Service
public class LdapServiceImpl implements ILdapService {

    @Autowired
    private LdapTemplate ldapTemplate;
    private static final Logger logger = LoggerFactory.getLogger(LdapServiceImpl.class);

    @Override
    public Boolean ldapAuth(String username, String password) {
        EqualsFilter filter = new EqualsFilter("uid", username);
        boolean authenticate;
        try{
            authenticate = ldapTemplate.authenticate("cn=employees, O=CAH", filter.toString(), password);
        } catch (Exception e){
            logger.error("ldap验证失败：{}", e.getMessage());
            throw new BaseServiceException(HttpStatusCode.CODE_500, "连接Ldap服务器失败！");
        }
        logger.info("方法名：ldapAuth，结果：" + authenticate);
        return authenticate;
    }

    @Override
    public User getAllPersonNames(String uid) {
        User user = new User();
        List<User> userList = ldapTemplate.search(
                query().base("cn=employees, O=CAH")
                        .where("uid").is(uid),
                new UserAttributesMapper());
        logger.info("方法名：getAllPersonNames，结果：" + userList);
        if (CollectionUtil.isNotEmpty(userList)) {
            user = userList.get(0);
        }
        return user;
    }

    @Override
    public Organization getOrgByUid(String uid) {
        User user = getAllPersonNames(uid);
        List<Organization> allOrgsById = getAllOrgsById(user.getDepartmentNumber());
        return allOrgsById.stream().findFirst().orElse(null);
    }

    @Override
    public List<User> getAllPerson() {
        List<User> userList = ldapTemplate.search(
                query().base("cn=employees, O=CAH"),
                new UserAttributesMapper());
        logger.info("方法名：getAllPerson，结果：" + userList);
        return userList;
    }

    @Override
    public List<Organization> getAllOrgsById(String departmentNumber) {
        List<Organization> organizationList = ldapTemplate.search(
                query().base("cn=orgs, O=CAH")
                        .where("cahTopnodeCode").is("62").and("ou").is(departmentNumber),
                new OraganizationMapper());
        logger.info("方法名：getAllOrgsById，结果：" + organizationList);
        return organizationList;
    }

    @Override
    public List<Organization> getAllOrgsByNmae(String cahOrgName) {
        List<Organization> organizationList = ldapTemplate.search(
                query().base("cn=orgs, O=CAH")
                        .where("cahTopnodeCode").is("62").and("cahOrgName").is(cahOrgName),
                new OraganizationMapper());
        logger.info("方法名：getAllOrgsByNmae，结果：" + organizationList);
        return organizationList;
    }

    @Override
    public boolean is62User(String uid) {
        boolean result = false;
        List<User> users = ldapTemplate.search(
                query().base("cn=employees, O=CAH")
                        .where("uid").is(uid),
                new UserAttributesMapper());
        if (CollectionUtil.isNotEmpty(users)) {
            String departmentNumber = users.get(0).getDepartmentNumber();
            List<Organization>  organizationList = ldapTemplate.search(
                    query().base("cn=orgs, O=CAH")
                            .where("cahTopnodeCode").is("62").and("ou").is(departmentNumber),
                    new OraganizationMapper());
            result = CollectionUtil.isNotEmpty(organizationList);
        }
        return result;
    }


}
